/**
 * mediaItem provider gets acsses to the mediaItem database
 * @param db 
 * @returns {___anonymous1431_1493}
 */

module.exports = function(db){
	var Items = db.collection('mediaItems');
	var Dirs = db.collection('mediaDirs');
	
	
	var getMedia = function(url, depth, callback){
		if(url.lastIndexOf("/") == url.length-1)url = url.substr(0, url.length-1);
		url = escape(url);
		var regex = new RegExp("^"+url+"(\/[a-zA-Z0-9äöüÄÖÜß%#$;+_@?=: \-]+?){0,"+depth+"}(\/[a-zA-Z0-9äöüÄÖÜß%#$;+_@?=: \-]+?\.(mp3|ogg))$");	
		Items.find({Url: regex }).toArray(function(err, results) {
			console.log('res',results);
        	if(err) callback(err);
        	callback(null, results);
        });
	};

	var getMediaStructur = function(url, depth, callback){
		//  /^(\/[a-z0-9äöüÄÖÜß-._@?=: ;+%#$]*){2}$/i
		url = escape(url);
		var regex = new RegExp("^"+url+"(\/[a-zA-Z0-9äöüÄÖÜß%#$;+._@?=: \-]+?){1,"+ depth +"}$");	
		Dirs.find().toArray(function(err, results) {
        	if(err) callback(err);
        	callback(null, results);
        });
	};
	
	var addDir = function(dir, fn){
		Dirs.save(dir, function(err, saved) {
			fn(err, saved);
        });
	};
	var addItem = function(songs, fn){
		Items.save(songs, function(err, saved) {
			fn(err, saved);
        });
	};

	

	return {
		getMediaStructur: getMediaStructur,
		getMedia: getMedia,
		addDir: addDir,
		addItem: addItem,

	};
};
